import { constantRoutes } from "../../route.config";
import { LoginService } from "@/api/user";
import layout from "@/layout/index.vue";
import url from "@/api/common.ts";
const Logout = url.Logout;
const state = {
  publicKey:
    "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCdmxuizItCImkCdAamybkvxzXjhCWTx+3SkCqBoPgv4yovTno1Nd4TbQSp8S2wj395vzMI7v4NR3tZgExrzWUnTce9tbGgRUIGuKXfSl5NwTPPIQLk5XPLRb9/LfMDhqVC0E/jll8c/pMwPliW37kRuclsE7P8r5hMJyk7HGiDfwIDAQAB",
  menuBig: true,
  routes: [],
  addRoutes: [],
  tabList: [
    {
      name: "/userList",
      path: "/userList",
      meta: {
        title: "用户管理",
      },
    },
  ],
  theMenuName: "/userList",
  menuList: [],
  userInfo: {},
  roles: [],
  permissions: [],
  cfcaip: "",
};
// 匹配views里面所有的.vue文件
const modules = import.meta.glob("@/pages/**/*.vue");
const loadView = (view: any) => {
  let res;
  for (const path in modules) {
    const dir = path.split("pages/")[1].split(".vue")[0];
    if (dir === view) {
      res = () => modules[path]();
    }
  }
  return res;
};

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap: any) {
  return asyncRouterMap.filter((route: any) => {
    if (route.menuType == "M") {
      route.component = layout;
    } else {
      route.component = loadView(route.component);
    }
    if (route.children && route.children.length > 0) {
      route.children = filterAsyncRouter(route.children);
    }
    return true;
  });
}
function tagList(commit, tagArr, obj) {
  tagArr.forEach((el) => {
    if (el.path == obj.path) {
      commit("SET_TAB", { ...el, query: obj.query });
      commit("SET_TABNAME", el.name);
    }
    if (el.children) {
      tagList(commit, el.children, obj);
    }
  });
}
function menuFunList(menuArrList) {
  return menuArrList.filter((r) => {
    if (r.children && r.children.length > 0) {
      r.children = menuFunList(r.children);
    }
    return !r.hidden;
  });
}
const getters = {
  menuBig: (state: any) => {
    return state.menuBig;
  },
  tabList: (state: any) => {
    return state.tabList;
  },
  theMenuName: (state: any) => {
    return state.theMenuName;
  },
  menuList: (state: any) => state.menuList,
  userInfo: (state: any) => state.userInfo,
  permissions: (state: any) => state.permissions,
  roles: (state: any) => state.roles,
  publicKey: (state: any) => state.publicKey,
  cfcaip: (state: any) => state.cfcaip,
};
const mutations = {
  SET_MENU_BIG(state: any, value: boolean) {
    state.menuBig = value;
  },
  SET_TAB(state: any, value: any) {
    state.tabList.push(value);
    const obj = {};
    const res = state.tabList.reduce(function (
      preValue: any[],
      item: { path: string | number }
    ) {
      obj[item.path] ? "" : (obj[item.path] = true && preValue.push(item));
      return preValue;
    },
    []);
    state.tabList = res;
    sessionStorage.setItem("tabList", JSON.stringify(state.tabList));
  },
  SET_TABNAME(state: any, name: string) {
    state.theMenuName = name;
    sessionStorage.setItem("tabName", name);
  },
  DEL_TAB(state: any, value: number) {
    state.tabList.splice(value, 1);
    sessionStorage.setItem("tabList", JSON.stringify(state.tabList));
  },
  SET_ROUTES: (state: any, routes: any) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
  },
  SET_MENU_LIST: (state: any, list: Array) => {
    state.menuList = list;
  },
  SET_USER: (state: any, obj: any) => {
    state.userInfo = obj;
  },
  SET_ROLES: (state: any, obj: any) => {
    state.roles = obj;
  },
  SET_PERMISSIONS: (state: any, obj: any) => {
    state.permissions = obj;
  },
  SET_IP: (state: any, obj: any) => {
    state.cfcaip = obj;
  },
};
const actions = {
  setMenuBig({ commit }: any, value: boolean) {
    commit("SET_MENU_BIG", value);
  },
  setTab({ commit }: any, obj: any) {
    if (obj.path == "/" || obj.path == "/userList") {
      commit("SET_TABNAME", "/userList");
      return;
    }
    const tabList: any = state.tabList;
    let flag = false;
    for (let j = 0; j < tabList.length; j++) {
      if (tabList[j].path == obj.path) {
        tabList[j].query = obj.query;
        sessionStorage.setItem("tabList", JSON.stringify(tabList));
        commit("SET_TABNAME", tabList[j].name);
        flag = true;
        break;
      }
    }
    if (!flag) {
      const menuList = state.routes;
      tagList(commit, menuList, obj);
    }
  },
  delTab({ commit }: any, path: any) {
    const tabList = state.tabList;
    const id = tabList.findIndex((item) => {
      return item.name == path.name;
    });
    commit("DEL_TAB", id);
  },
  getUserInfo({ commit }: any) {
    return new Promise((resolve) => {
      LoginService.userInfo({})
        .then((res: any) => {
          if (res.code == 200) {
            commit("SET_USER", res.user);
            commit("SET_ROLES", res.roles);
            commit("SET_PERMISSIONS", res.permissions);
            commit("SET_IP", res.IP);
            resolve(res.user);
          } else {
            Logout();
          }
        })
        .catch((error) => {
          Logout();
        });
    });
  },
  getRouterList({ commit }: any) {
    return new Promise((resolve) => {
      LoginService.Menu({}).then((res:any) => {
        res.data.push({
          path: "/:catchAll(.*)",
          name: "404",
          component: "error/index",
        });
        const rdata = JSON.parse(JSON.stringify(res.data));
        const mdata = JSON.parse(JSON.stringify(res.data));
        const rewriteRoutes = filterAsyncRouter(rdata);
        const menuArrList = menuFunList(mdata).filter((r) => r.menuType != "C");
        commit("SET_ROUTES", rewriteRoutes);
        commit("SET_MENU_LIST", menuArrList);
        resolve(rewriteRoutes);
      });
    });
  },
};

export default {
  state,
  actions,
  mutations,
  getters,
};
